import React, { useState, useEffect } from 'react';
import { Toast } from 'antd-mobile';
import axiosInstance from '../api/axios';
import { endpoints } from '../api/endpoints';
import { getEndpoint } from '../utils/storage';

const StoreSelector = ({ visible, onClose, onSelectStore }) => {
  const [stores, setStores] = useState([]);
  const [loading, setLoading] = useState(false);
  const [imageIndices, setImageIndices] = useState({});

  // 获取商户列表
  const fetchStores = async () => {
    setLoading(true);
    try {
      const res = await axiosInstance.get(endpoints.getStoreList, {
        params: {
          page: 1,
          perPage: 40,
          sort: '-created',
          skipTotal: 1,
          filter: 'status=true'
        },
      });
      setStores(res.data.items || []);
    } catch (error) {
      console.error('获取商户列表失败:', error);
      Toast.show({ content: '获取商户列表失败', position: 'center' });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (visible) {
      fetchStores();
    }
  }, [visible]);

  // 轮播图控制
  const nextImage = (storeId) => {
    const store = stores.find(s => s.id === storeId);
    if (store && store.images && store.images.length > 1) {
      setImageIndices(prev => ({
        ...prev,
        [storeId]: (prev[storeId] || 0) === store.images.length - 1 ? 0 : (prev[storeId] || 0) + 1
      }));
    }
  };

  const prevImage = (storeId) => {
    const store = stores.find(s => s.id === storeId);
    if (store && store.images && store.images.length > 1) {
      setImageIndices(prev => ({
        ...prev,
        [storeId]: (prev[storeId] || 0) === 0 ? store.images.length - 1 : (prev[storeId] || 0) - 1
      }));
    }
  };

  // 选择商户
  const handleSelectStore = (store) => {
    onSelectStore(store);
    onClose();
  };

  // 轮播图组件
  const ImageCarousel = ({ store }) => {
    if (!store.images || store.images.length === 0) {
      return (
        <div style={{
          width: '100%',
          height: '180px',
          backgroundColor: '#f5f5f5',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          borderRadius: '12px',
          color: '#999',
          fontSize: '16px'
        }}>
          暂无图片
        </div>
      );
    }

    return (
      <div style={{ position: 'relative', width: '100%', height: '180px' }}>
        <img
          src={`${getEndpoint()}/api/files/${store.collectionId}/${store.id}/${store.images[imageIndices[store.id] || 0]}`}
          alt={store.store_name}
          style={{
            width: '100%',
            height: '100%',
            objectFit: 'cover',
            borderRadius: '12px'
          }}
        />
        {store.images.length > 1 && (
          <>
            <button
              onClick={(e) => {
                e.stopPropagation();
                prevImage(store.id);
              }}
              style={{
                position: 'absolute',
                left: '12px',
                top: '50%',
                transform: 'translateY(-50%)',
                background: 'rgba(0,0,0,0.6)',
                color: 'white',
                border: 'none',
                borderRadius: '50%',
                width: '32px',
                height: '32px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                cursor: 'pointer',
                fontSize: '16px',
                transition: 'background 0.2s'
              }}
              onMouseEnter={(e) => e.target.style.background = 'rgba(0,0,0,0.8)'}
              onMouseLeave={(e) => e.target.style.background = 'rgba(0,0,0,0.6)'}
            >
              ‹
            </button>
            <button
              onClick={(e) => {
                e.stopPropagation();
                nextImage(store.id);
              }}
              style={{
                position: 'absolute',
                right: '12px',
                top: '50%',
                transform: 'translateY(-50%)',
                background: 'rgba(0,0,0,0.6)',
                color: 'white',
                border: 'none',
                borderRadius: '50%',
                width: '32px',
                height: '32px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                cursor: 'pointer',
                fontSize: '16px',
                transition: 'background 0.2s'
              }}
              onMouseEnter={(e) => e.target.style.background = 'rgba(0,0,0,0.8)'}
              onMouseLeave={(e) => e.target.style.background = 'rgba(0,0,0,0.6)'}
            >
              ›
            </button>
            <div style={{
              position: 'absolute',
              bottom: '12px',
              left: '50%',
              transform: 'translateX(-50%)',
              display: 'flex',
              gap: '6px'
            }}>
              {store.images.map((_, index) => (
                <div
                  key={index}
                  style={{
                    width: '8px',
                    height: '8px',
                    borderRadius: '50%',
                    backgroundColor: index === (imageIndices[store.id] || 0) ? 'white' : 'rgba(255,255,255,0.6)',
                    transition: 'background 0.2s'
                  }}
                />
              ))}
            </div>
          </>
        )}
      </div>
    );
  };

  // 商户卡片组件
  const StoreCard = ({ store }) => (
    <div
      style={{
        background: 'white',
        borderRadius: '16px',
        padding: '20px',
        marginBottom: '16px',
        boxShadow: '0 4px 16px rgba(0,0,0,0.08)',
        cursor: 'pointer',
        transition: 'all 0.3s ease',
        border: '1px solid #f0f0f0'
      }}
      onMouseEnter={(e) => {
        e.currentTarget.style.transform = 'translateY(-4px)';
        e.currentTarget.style.boxShadow = '0 8px 24px rgba(0,0,0,0.12)';
        e.currentTarget.style.borderColor = '#e6f7ff';
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.transform = 'translateY(0)';
        e.currentTarget.style.boxShadow = '0 4px 16px rgba(0,0,0,0.08)';
        e.currentTarget.style.borderColor = '#f0f0f0';
      }}
      onClick={() => handleSelectStore(store)}
    >
      <ImageCarousel store={store} />
      
      <div style={{ marginTop: '16px' }}>
        <h3 style={{
          margin: '0 0 12px 0',
          fontSize: '20px',
          fontWeight: '600',
          color: '#333',
          lineHeight: '1.3'
        }}>
          {store.store_name}
        </h3>
        
        <p style={{
          margin: '0 0 12px 0',
          fontSize: '15px',
          color: '#666',
          lineHeight: '1.5',
          minHeight: '45px'
        }}>
          {store.stpre_desc}
        </p>
        
        <div style={{
          marginBottom: '8px',
          fontSize: '14px',
          color: '#999',
          display: 'flex',
          alignItems: 'center',
          gap: '6px'
        }}>
          <span style={{ fontSize: '16px' }}>📍</span>
          <span>{store.store_address}</span>
        </div>

        <div style={{
          fontSize: '14px',
          color: '#1677ff',
          display: 'flex',
          alignItems: 'center',
          gap: '6px'
        }}>
          <span style={{ fontSize: '16px' }}>🕒</span>
          <span>{store.business_time}</span>
        </div>
      </div>
    </div>
  );

  if (!visible) return null;

  return (
    <div style={{
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      backgroundColor: '#f5f7fa',
      zIndex: 1000,
      display: 'flex',
      flexDirection: 'column'
    }}>
      {/* 头部 */}
      <div style={{
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        padding: '20px 24px',
        color: 'white',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
      }}>
        <h1 style={{
          margin: 0,
          fontSize: '24px',
          fontWeight: '600'
        }}>
          选择商户
        </h1>
        <button
          onClick={onClose}
          style={{
            background: 'rgba(255,255,255,0.2)',
            border: 'none',
            borderRadius: '50%',
            width: '40px',
            height: '40px',
            color: 'white',
            fontSize: '20px',
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            transition: 'background 0.2s'
          }}
          onMouseEnter={(e) => e.target.style.background = 'rgba(255,255,255,0.3)'}
          onMouseLeave={(e) => e.target.style.background = 'rgba(255,255,255,0.2)'}
        >
          ✕
        </button>
      </div>

      {/* 内容区域 */}
      <div style={{
        flex: 1,
        padding: '24px',
        overflow: 'auto',
        maxWidth: '1200px',
        margin: '0 auto',
        width: '100%'
      }}>
        {loading ? (
          <div style={{
            textAlign: 'center',
            padding: '80px 0',
            color: '#999',
            fontSize: '16px'
          }}>
            <div style={{ marginBottom: '16px' }}>⏳</div>
            加载中...
          </div>
        ) : stores.length === 0 ? (
          <div style={{
            textAlign: 'center',
            padding: '80px 0',
            color: '#999',
            fontSize: '16px'
          }}>
            <div style={{ marginBottom: '16px', fontSize: '48px' }}>🏪</div>
            敬请期待更多商户入驻
          </div>
        ) : (
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(350px, 1fr))',
            gap: '20px',
            padding: '0'
          }}>
            {stores.map(store => (
              <StoreCard key={store.id} store={store} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default StoreSelector; 